import React, { useState, useEffect } from 'react';
import { View, Text, FlatList, Image, TouchableOpacity, StyleSheet } from 'react-native';
import api from '../services/api';
import CustomHeader from '../components/CustomHeader';

const ChatTabsScreen = ({ navigation }) => {
  const [activeTab, setActiveTab] = useState('chat');
  const [conversations, setConversations] = useState([]);
  const [likes, setLikes] = useState([]);
  const [visitors, setVisitors] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchConversations();
  }, []);

  const fetchConversations = async () => {
    setLoading(true);
    try {
      const response = await api.getConversations();
      if (response.success) {
        setConversations(response.data);
      }
    } catch (error) {
      console.error('获取会话列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const renderChatItem = ({ item }) => (
    <TouchableOpacity 
      style={styles.chatItem}
      onPress={() => navigation.navigate('Chat', { matchId: item.id, matchName: item.name })}
    >
      <Image 
        source={{ uri: item.avatar || 'https://via.placeholder.com/50' }} 
        style={styles.avatar}
      />
      <View style={styles.chatInfo}>
        <Text style={styles.chatName}>{item.name || '匿名用户'}</Text>
        <Text style={styles.lastMessage} numberOfLines={1}>
          {item.lastMessage || '暂无消息'}
        </Text>
      </View>
      <Text style={styles.timestamp}>
        {item.lastMessageTime ? new Date(item.lastMessageTime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}
      </Text>
    </TouchableOpacity>
  );

  const renderLikeItem = ({ item }) => (
    <TouchableOpacity style={styles.interactionItem}>
      <Image 
        source={{ uri: item.avatar || 'https://via.placeholder.com/50' }} 
        style={styles.avatar}
      />
      <View style={styles.interactionInfo}>
        <Text style={styles.interactionName}>{item.name || '匿名用户'}</Text>
        <Text style={styles.interactionDetail}>赞了你</Text>
      </View>
      <Text style={styles.interactionTime}>
        {item.time ? new Date(item.time).toLocaleDateString() : ''}
      </Text>
    </TouchableOpacity>
  );

  const renderVisitorItem = ({ item }) => (
    <TouchableOpacity style={styles.interactionItem}>
      <Image 
        source={{ uri: item.avatar || 'https://via.placeholder.com/50' }} 
        style={styles.avatar}
      />
      <View style={styles.interactionInfo}>
        <Text style={styles.interactionName}>{item.name || '匿名用户'}</Text>
        <Text style={styles.interactionDetail}>访问了你的主页</Text>
      </View>
      <Text style={styles.interactionTime}>
        {item.time ? new Date(item.time).toLocaleDateString() : ''}
      </Text>
    </TouchableOpacity>
  );

  const renderContent = () => {
    switch (activeTab) {
      case 'chat':
        return (
          <FlatList
            data={conversations}
            renderItem={renderChatItem}
            keyExtractor={(item) => item.id.toString()}
            style={styles.contentList}
            onRefresh={fetchConversations}
            refreshing={loading}
          />
        );
      case 'likes':
        return (
          <FlatList
            data={likes}
            renderItem={renderLikeItem}
            keyExtractor={(item) => item.id.toString()}
            style={styles.contentList}
          />
        );
      case 'visitors':
        return (
          <FlatList
            data={visitors}
            renderItem={renderVisitorItem}
            keyExtractor={(item) => item.id.toString()}
            style={styles.contentList}
          />
        );
      default:
        return null;
    }
  };

  return (
    <View style={styles.container}>
      <CustomHeader title="聊天" showMenuButton={true} />
      
      {/* 顶部标签导航 */}
      <View style={styles.tabContainer}>
        <TouchableOpacity
          style={[styles.tab, activeTab === 'chat' && styles.activeTab]}
          onPress={() => setActiveTab('chat')}
        >
          <Text style={[styles.tabText, activeTab === 'chat' && styles.activeTabText]}>
            聊天
          </Text>
        </TouchableOpacity>
        
        <TouchableOpacity
          style={[styles.tab, activeTab === 'likes' && styles.activeTab]}
          onPress={() => setActiveTab('likes')}
        >
          <Text style={[styles.tabText, activeTab === 'likes' && styles.activeTabText]}>
            赞
          </Text>
        </TouchableOpacity>
        
        <TouchableOpacity
          style={[styles.tab, activeTab === 'visitors' && styles.activeTab]}
          onPress={() => setActiveTab('visitors')}
        >
          <Text style={[styles.tabText, activeTab === 'visitors' && styles.activeTabText]}>
            访客
          </Text>
        </TouchableOpacity>
      </View>
      
      {/* 内容区域 */}
      <View style={styles.content}>
        {renderContent()}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  tabContainer: {
    flexDirection: 'row',
    backgroundColor: '#2196F3',
    paddingVertical: 10,
  },
  tab: {
    flex: 1,
    alignItems: 'center',
    paddingVertical: 10,
  },
  activeTab: {
    borderBottomWidth: 3,
    borderBottomColor: 'white',
  },
  tabText: {
    color: 'rgba(255, 255, 255, 0.7)',
    fontSize: 16,
    fontWeight: 'bold',
  },
  activeTabText: {
    color: 'white',
  },
  content: {
    flex: 1,
  },
  contentList: {
    flex: 1,
  },
  chatItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  interactionItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 25,
    marginRight: 16,
  },
  chatInfo: {
    flex: 1,
  },
  interactionInfo: {
    flex: 1,
  },
  chatName: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  interactionName: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  lastMessage: {
    fontSize: 14,
    color: 'gray',
    marginTop: 4,
  },
  interactionDetail: {
    fontSize: 14,
    color: 'gray',
    marginTop: 4,
  },
  timestamp: {
    fontSize: 12,
    color: 'gray',
  },
  interactionTime: {
    fontSize: 12,
    color: 'gray',
  },
});

export default ChatTabsScreen;